<template>
  <!-- <div class="addTabProject"> 55vw-->
    <a-drawer
      title="自定义标签"
      :width="'1080px'"
      :visible="addTabDrawerVisible"
      :maskClosable="false"
      :body-style="{ paddingBottom: '80px', paddingTop: '16px' }"
      @close="onClose"
    >
      <div class="tabNameBox">
        <div class="title">自定义名称</div>
        <div class="inputStyle">
          <div class="name">页签名称：</div>
          <div class="input_name">
            <a-input v-model="tabName" placeholder="请输入名称（8个字以内）" />
          </div>
        </div>
      </div>
      <div class="selectFilter">
        <div class="titleSearch">
          <span class="title">项目列表</span>
          <!--<div class="searchInput">
            <span class="inputName">已选项目
              <i>（共{{tabsTableArr.length}}个）</i>
            </span>
            <global-search :searchTableData="searchTable" @onSearch="drawTableSearch"></global-search>
          </div>-->
          <div class="buttonVisible">
            <!--<a-button type="primary" @click="btnClick"></a-button>-->
            <a-icon type="filter" />
            <span @click="btnClick">{{ searchVisible ? '展开筛选' : '收起筛选'}}</span>
          </div>
        </div>
        <div class="selectCodition" :class="searchVisible ? 'searchVisible' : ''">
          <!-- 所属部门 -->
          <div class="selectItem">
            <span class="selectTitle">所属部门：</span>
            <a-select v-model="groupInfo" :allowClear="true" @change="ValueChange" :showSearch="true" mode="multiple" >
              <a-select-option v-for="item in userGroupList" :key="item.groupOid" :value="item.groupName" >
                <!-- <a-tooltip placement="topLeft">
                  <template slot="title">
                    {{ item.groupName }}
                  </template> -->
                  {{ item.groupName }}
                <!-- </a-tooltip> -->
              </a-select-option>
            </a-select>
          </div>
          <!-- 项目状态 -->
          <div class="selectItem">
            <span class="selectTitle">项目状态：</span>
            <a-select v-model="projectState" :allowClear="true" @change="ValueChange" mode="multiple" >
              <a-select-option v-for="(item, index) in projectStatusList" :key="index" :value="item.lable" >
                {{ item.lable }}
              </a-select-option>
            </a-select>
          </div>
          <!-- 项目大类 -->
          <div class="selectItem">
            <span class="selectTitle">项目大类：</span>
            <a-select v-model="selectObj.projectType" :allowClear="true" @change="projectBigTypeChange">
              <a-select-option v-for="(item, index) in projectBigType" :key="index" :value="item.name">
                {{ item.displayName }}
              </a-select-option>
            </a-select>
          </div>
          <!-- 项目小类 -->
          <div class="selectItem">
            <span class="selectTitle">项目小类：</span>
            <a-select v-model="selectObj.projectSmallType" :allowClear="true" @change="ValueChange" @dropdownVisibleChange="dropdownVisibleChange">
              <a-select-option v-for="item in projectSmallTypeOption" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </div>
          <!-- 项目等级 -->
          <div class="selectItem">
            <span class="selectTitle">重要等级：</span>
            <a-select v-model="selectObj.importantGrade" :allowClear="true" @change="ValueChange" @dropdownVisibleChange="dropdownVisibleChange">
              <a-select-option v-for="item in importantGradeOption" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </div>
          <!-- 细分类型 -->
          <div class="selectItem">
            <span class="selectTitle">细分类型：</span>
            <a-select v-model="selectObj.nsegmenttype" :allowClear="true" @change="ValueChange" @dropdownVisibleChange="dropdownVisibleChange">
              <a-select-option v-for="item in nsegmenttypeOption" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </div>
          <!--开展方式-->
          <div class="selectItem">
            <span class="selectTitle">开展方式：</span>
            <a-select v-model="selectObj.modeofdevelopment" :allowClear="true" @change="ValueChange" @dropdownVisibleChange="dropdownVisibleChange">
              <a-select-option v-for="item in modeofdevelopmentOption" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </div>
          <!-- 当前关键节点 -->
          <div class="selectItem">
            <span class="selectTitle">关键节点：</span>
            <a-input v-model="selectObj.currentnode" style="width: 165px" placeholder="请输入" @change="ValueChange" />
          </div>
          <!-- 当前关键节点计划完成时间 -->
          <div class="selectItem">
            <span class="selectTitle">当前关键节点计划完成时间：</span>
            <a-range-picker v-model="currentTime" style="width: 307px" @change="timeChange" />
          </div>
        </div>
        
      </div>
      <!--@selectedRows="selectedRows" :isSelectKey="isSelectKey"        
        :this-table-name="'tabContentList'"
        :this-table-header-data="thisTableHeaderData"
        :this-table-header-data-middel="thisTableHeaderDataMiddel"-->
      <div class="drawTabel">
        <draw-tale
          :columns="columns"
          :tableData="tabsTableArr"
          data-row-key="oid"
          :selectType="'checkbox'"
          :loadVisible="loadVisible"
          :isRowsSelectVisible="false"
          ref="table"
          scrollY='calc(100vh - 517px)'
        ></draw-tale>
      </div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          取消
        </a-button>
        <a-button type="primary" @click="confirm">
          确定
        </a-button>
      </div>
    </a-drawer>
  <!-- </div> -->
</template>
<script>
import moment from 'moment'
import { getTabTablesData, setUserProjectFilters, getUserProjectFilters, getProjectAttribute, getPIProjectsUserGroup, getLifeCycleTemplate } from "@/api/projectManage.js"
import { getProjectType, getCreateProject } from "@/api/singleProject.js"
import { userinfo } from '@/api/middleGround'
import drawTale from "@/components/common/commonTable";
import globalSearch from "@/components/common/globalSearch"
import cloneData from 'lodash'
let userInfo = userinfo
export default {
  name: 'addTabProject',
  components: {
    drawTale,
    globalSearch
  },
  /*抽屉显示隐藏，抽屉里面表格表头，当前用户所展示的数据*/
  props: ['addTabDrawerVisible', 'addTabColumns', 'projectPermissionDataOid'],
  data() {
    return {
      searchVisible: true, 
      searchTable: [], 
      currentTime: [],
      tagIds: null, // 标签ID
      tabName: '', // 标签名
      selectObj: { // 下拉框表单值
        projectGroupReference: '',
        state: '',
        projectType: '',
        projectSmallType: '',
        importantGrade: '',
        nsegmenttype: '',
        modeofdevelopment: '',
        currentnode: '',
        currentnodeTargetTime: ''
      },
      groupInfo: [], // 所属组织
      projectState: [], //状态
      projectBigType: [],// 项目大类
      userGroupList: [], // 用户组织
      projectStatusList: [], // 项目状态
      otherTypeList: [], // 其他筛选条件
      /* 表格入参 */
      loadVisible: false, // loading
      columns: [
        {
          align: "left",
          dataIndex: "projectname",
          displayName: "名称",
          name: "projectname",
          title: "名称",
        },
        {
          align: "left",
          dataIndex: "projectshortname",
          displayName: "编码",
          name: "projectshortname",
          title: "编码",
        },
        {
          align: "left",
          dataIndex: "projectmananger",
          displayName: "项目经理",
          name: "projectmananger",
          title: "项目经理",
        },
        {
          align: "left",
          dataIndex: "projectgroupreference",
          displayName: "所属组织",
          name: "projectgroupreference",
          title: "所属组织",
        },
        {
          align: "left",
          dataIndex: "state",
          displayName: "项目状态",
          name: "state",
          title: "项目状态",
        },
        {
          align: "left",
          dataIndex: "projecttype",
          displayName: "项目大类",
          name: "projecttype",
          title: "项目大类",
        },
        {
          align: "left",
          dataIndex: "projectsmalltype",
          displayName: "项目小类",
          name: "projectsmalltype",
          title: "项目小类",
        },
        {
          align: "left",
          dataIndex: "importantgrade",
          displayName: "重要等级",
          name: "importantgrade",
          title: "重要等级",
        },
        {
          align: "left",
          dataIndex: "nsegmenttype",
          displayName: "细分类型",
          name: "nsegmenttype",
          title: "细分类型",
        },
        {
          align: "left",
          dataIndex: "modeofdevelopment",
          displayName: "开展方式",
          name: "modeofdevelopment",
          title: "开展方式",
        },
        {
          align: "left",
          dataIndex: "currentnode",
          displayName: "当前关键节点",
          name: "currentnode",
          title: "当前关键节点",
        },
        {
          align: "left",
          dataIndex: "currentnodetargettime",
          displayName: "当前关键节点计划完成时间",
          name: "currentnodetargettime",
          title: "当前关键节点计划完成时间",
        }
      ],
      tabsTableArr: [], // 当前表格数据
      // healthStatusImg: '', // 健康状态图片
      healthStatusImgObj: { // 健康状态图片对象
        'green': require('@/assets/manageMain/green.svg'),
        'yellow': require('@/assets/manageMain/yellow.svg'),
        'red': require('@/assets/manageMain/red.svg'),
        'gray': require('@/assets/manageMain/gray.svg'),
      },
      // thisTableHeaderData: [],//当前表格所有表头数据
      // thisTableHeaderDataMiddel: [],//当前表格存在中台的表头数据
      // modeofdevelopmentOption: [],
    }
  },
  watch: {
    /* 抽屉表头数据 */
    addTabColumns(val, oldVal) {
      this.addTabColumns = val
    },
    addTabDrawerVisible(val, oldVal) {
      this.addTabDrawerVisible = val
      if (this.addTabDrawerVisible) {
        this.searchVisible = false
        this.loadVisible = true
        this.getFilterData()
        this.initData()
      }
    },
    loadNum(value) {
      if (this.$store.state.loadTable.tableName === 'tabContentList') {
        this.getMiddleHeaderData('tabContentList')
      }
    },
  },
  computed: {
    loadNum() {
      return this.$store.state.loadTable.num
    },//vuex数据，表头设置点击“确定”，刷新数据
    projectSmallTypeOption() {
      if (this.otherTypeList.length > 0) {
        let arr = this.otherTypeList.filter(item => item.id === 'ProjectSmallType')
        if (arr && arr.length > 0) {
          return arr[0].selects
        } else {
          return {}
        }
      } else {
        return {}
      }
      
    },
    importantGradeOption() {
      if (this.otherTypeList.length > 0) {
        let arr = this.otherTypeList.filter(item => item.id === 'ImportantGrade')
        if (arr && arr.length > 0) {
          return arr[0].selects
        } else {
          return {}
        }
      } else {
        return {}
      }
    },
    nsegmenttypeOption() {
      if (this.otherTypeList.length > 0) {
        let arr = this.otherTypeList.filter(item => item.id === 'nsegmenttype')
        if (arr && arr.length > 0) {
          return arr[0].selects
        } else {
          return {}
        }
      } else {
        return {}
      }
    },
    modeofdevelopmentOption() {
      if (this.otherTypeList.length > 0) {
        let arr = this.otherTypeList.filter(item => item.id === 'modeofdevelopment')
        if (arr && arr.length > 0) {
          return arr[0].selects
        } else {
          return {}
        }
      } else {
        return {}
      }
    }
  },
  mounted() {},
  methods: {
    moment,
    initData() {
      // this.getMiddleHeaderData('tabContentList')
      // this.getColumns([])
      this.getBigType()
      this.getUserGroupData()
    },
    // 抽屉
    onClose() {
      this.$emit('drawClose')
      this.tabName = ''
    },
    // 搜索条件显示隐藏
    btnClick() {
      this.searchVisible = !this.searchVisible
    },
    // 全局搜索
    // drawTableSearch(tableVal, searchValue) {
    //   this.loadVisible = true
    //   if (!searchValue) {
    //     // 当传过来的数据为空，并且输入条件为空时，重新调用
    //     this.getTableData()
    //   } else {
    //     this.loadVisible = false
    //     this.tabsTableArr = tableVal
    //   }
    // },
    // 获取项目大类
    getBigType() {
      let data = {
        objType: 'com.pisx.pmgt.project.PIProject'
      }
      getProjectType(data).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.data.length > 0) {
            this.projectBigType = res.data.data
          } else {
            this.projectBigType = []
          }
        }
      })
    },
    // 获取用户组
    getUserGroupData() {
      getPIProjectsUserGroup({userId: userInfo.loginName}).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.data.length > 0) {
            this.userGroupList = res.data.data
          } else {
            this.userGroupList = []
          }
        }
      })
    },
    // 获取项目状态
    geiPorjectStatus(val) {
      let data = {
        oid: 'OR:com.pisx.pmgt.project.PIProject:' + val.oid
      }
      getLifeCycleTemplate(data).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.data.length > 0) {
            this.projectStatusList = res.data.data[0].selects
          } else {
            this.projectStatusList = []
          }
        }
      })
    },
    // 筛选
    ValueChange(value) {
      this.getTableData()
    },
    dropdownVisibleChange(open) {
      if (!this.selectObj.projectType && open) {
        this.$message.warn('请选择项目大类！')
      }
    },
    // 获取其他筛选条件
    projectBigTypeChange(value) {
      if (!value) {
        this.otherTypeList = []
        this.selectObj = { // 下拉框表单值
          projectType: '',
          projectSmallType: '',
          importantGrade: '',
          nsegmenttype: '',
        }
        this.getTableData()
      } else {
        let arr = this.projectBigType.filter( v => v.name === value)
        if (arr && arr.length > 0) {
          this.selectObj.projectType = arr[0].displayName
        }
        let data = {
          "objType": value
        }
        
        getCreateProject(data).then(res => {
          if (res && res.status === 200) {
            if (res.data && res.data.data.length > 0) {
              let arrs =  res.data.data[0].rows
              let newArr = []
              arrs.map(it => {
                it.items.map(e => {
                  newArr.push(e)
                })
              })
              this.otherTypeList = newArr
              this.getTableData()
            } else {
              this.otherTypeList = []
              this.getTableData()
            }
          } else {
            this.getTableData()
          }
        })
      }
    },
    timeChange(date) {
      if (date.length > 0) {
        let startTime = date[0].format('YYYY-MM-DD 00:00:00')
        let endTime = date[1].format('YYYY-MM-DD 23:59:59')
        this.selectObj.currentnodeTargetTime = startTime + "#" + endTime
      } else {
        this.selectObj.currentnodeTargetTime = ""
      }
      this.getTableData()
    },
    // 获取表头
    getColumns(headersData) {
      let params = {
        type: "com.pisx.pmgt.project.PIProject"
      }
      getProjectAttribute(params).then(res => {
        if (res && res.status === 200) {
          this.columns = [];
          if (res.data && res.data.data.length > 0) { 
            let dataArr = res.data.data
            // this.thisTableHeaderData = dataArr;//所有表格头数据
            // 过滤掉设置项
            dataArr = dataArr.filter(e => {
              return e.dataIndex !== "setting";
            });
            let columnData = dataArr;
            columnData.forEach((item, index) => {
              // 项目名称
              if (item.name !== "projectgroupreference" && item.name !== "state" && item.name !== "projecttype" 
              && item.name !== "projectsmalltype" && item.name !== "importantgrade" && item.name !== "nsegmenttype" 
              && item.name !== "currentnode" && item.name !== "currentnodetargettime" && item.name !== "projectName") {
                // if (item.name === "projectName") {
                //   item.scopedSlots = { customRender: "name" };
                // } else 
                if (item.name === "healthStatus") {
                  item.scopedSlots = { 
                    filterDropdown: "filterDropdown",
                    filterIcon: "filterIcon",
                    customRender: "img",
                  };
                } else {
                  item.scopedSlots = {
                    filterDropdown: "filterDropdown",
                    filterIcon: "filterIcon",
                    customRender: "customRender"
                  };
                }
              }
              item.name = item.name.toLowerCase()
            });
            // 处理数据
            let arrNew = []
            if (headersData.length > 0) {
              arrNew = _.filter(columnData, function (o) {
                return headersData.indexOf(o.displayName) !== -1;
              })
              arrNew = _.sortBy(arrNew, (rec) => {
                return headersData.indexOf(rec.displayName)
              })
            } else {
              arrNew = columnData
            }
            
            // arrNew.push({
            //   dataIndex: "setting",
            //   fixed: "right",
            //   width: 40,
            //   slots: { title: "customTitle" }
            // });
            this.columns = arrNew;
          }
        } else {
          this.$message.error('获取表头失败')
        }
      }).catch(error => {
        this.isRowsSelectVisible = false
        this.$message.error('获取表头异常')
      })
    },
    // 获取表格数据
    getTableData() {
      let _this = this
      _this.loadVisible = true
      _this.tabsTableArr = []
      _this.selectObj.state = _this.projectState.join(',')
      _this.selectObj.projectGroupReference = _this.groupInfo.join(',')
      let params = _this.selectObj
      getTabTablesData(params).then(res => {
        if (res.status === 200) {
          if (res.data && res.data.length > 0) {
            res.data.map(item => {
              if (item.healthStatus === 'UNAVAILABLE') {
                item.healthStatusImg = _this.healthStatusImgObj.gray
              } else if (item.healthStatus === 'GREEN') {
                item.healthStatusImg = _this.healthStatusImgObj.green
              } else if (item.healthStatus === 'YELLOW') {
                item.healthStatusImg = _this.healthStatusImgObj.yellow
              } else if (item.healthStatus === 'RED') {
                item.healthStatusImg = _this.healthStatusImgObj.red
              }
              // 先全部转化为大写，然后再转化为小写(因为返回的字段中有全部是小写的情况)
              for (var key in item) {
                item[key.toUpperCase()] = item[key];
                delete (item[key]);
              }
            })
            res.data.map(it => {
              // 先全部转化为大写，然后再转化为小写
              for (var key in it) {
                it[key.toLowerCase()] = it[key];
                delete (it[key]);
              }
              it.key = it.oid
            })
            _this.loadVisible = false
            let handTableData = []
            let filterData = res.data
            filterData.forEach(m => {
              _this.projectPermissionDataOid.forEach(n => {
                if (m['oid'] === n.toString()) {
                  handTableData.push(m)
                }
              })
            })
            _this.tabsTableArr = cloneData.orderBy(handTableData, ['createstamp'], ['desc'])//按照创建时间降序排序
            _this.searchTable = cloneData.orderBy(handTableData, ['createstamp'], ['desc'])//按照创建时间降序排序
            // this.tabsTableArr = res.data
            // this.searchTable = res.data
            if (_this.projectStatusList.length === 0) {
              _this.geiPorjectStatus(_this.tabsTableArr[0] || '')
            }
          } else {
            _this.loadVisible = false
            _this.tabsTableArr = []
            _this.searchTable = []
          }
        } else {
          _this.loadVisible = false
          _this.$message.error("获取列表失败")
        }
      })
    },
    confirm() {
      this.setFilterData()
    },
    // 存储筛选数据
    setFilterData() {
      let data = {
        "tagName": this.tabName,
        "projectFilter": JSON.stringify(this.selectObj),
      }
      setUserProjectFilters(data).then(res => {
        if (res.status === 200) {
          this.submit()
        }
      })
    },
    // 获取存储的数据
    getFilterData() {
      if (this.tabName) {
        let that = this
        let data = {
          tagName: that.tabName,
          userId: userInfo.loginName,
        }
        getUserProjectFilters(data).then(res => {
          if (res.status === 200) {
            if (res.data && res.data.length > 0) {
              that.selectObj = JSON.parse(res.data[0].projectFilter)
              if (that.selectObj.state) {
                that.projectState = that.selectObj.state.split(',')
                that.groupInfo = that.selectObj.projectGroupReference.split(',')
              }
              if (that.selectObj.currentnodeTargetTime) {
                let startTime = that.selectObj.currentnodeTargetTime.split("#")[0].substring(0, 10)
                let endTime = that.selectObj.currentnodeTargetTime.split("#")[1].substring(0, 10)
                that.currentTime = [moment(startTime, 'YYYY-MM-DD'), moment(endTime, 'YYYY-MM-DD')]
              }
              that.getTableData()
            } else {
              that.getTableData()
            }
          } else {
            that.getTableData()
          }
        })
      } else {
        this.currentTime = []
        this.projectState = []
        this.groupInfo = []
        this.selectObj = { // 下拉框表单值
          projectGroupReference: '',
          state: '',
          projectType: '',
          projectSmallType: '',
          importantGrade: '',
          nsegmenttype: '',
          modeofdevelopment: '',
          currentnode: '',
          currentnodeTargetTime: ''
        }
        this.getTableData()
      }
    },
    // 提交
    submit() {
      let joinData= ''
      if (this.tabsTableArr.length > 0) {
        let arr = []
        this.tabsTableArr.forEach(o => {
          arr.push(o.oid)
        })
        joinData = arr.join(',')
      }
      let name = this.tabName.trim()
      if (name.length === 0) {
        this.$message.warn('请输入标签名！')
      } else if (name.length > 8) {
        this.$message.warn('标签名不能超过8个字')
      } else if (joinData.length === 0) {
        this.$message.warn('请筛选相关内容！')
      } else {
        this.$emit('drawConfirm', name, this.tagIds, joinData)
      }
    }
  }
  
}
</script>
<style lang="less" scoped>
.tabNameBox {
  width: 50%;
  margin-bottom: 12px;
  .title {
    font-weight: bold;
    font-style: normal;
    font-size: 16px;
    margin-bottom: 12px;
  }
  .inputStyle {
    display: flex;
    align-items: center;
    color: #333;
    
    .name {
      font-weight: 500;
      font-style: normal;
      font-size: 14px;
    }
    .input_name {
      width: 80%;
    }
  }
}
.selectFilter {
  margin-bottom: 16px;
  color: #333;
  .titleSearch {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #333;
    .title {
      font-weight: bold;
      font-style: normal;
      font-size: 16px;
    }
    .searchInput {
      display: flex;
      align-items: center;
      .inputName {
        margin-right: 0.5vw;
        i {
          color: #999999;
        }
      }
    }
    .buttonVisible {
      cursor: pointer;
    }
    .buttonVisible:hover {
      color: #386bd7;
    }
  }
  .selectCodition {
    // height: 170px;
    height: auto;
    transition: all 0.5s;
    .selectItem {
      display: inline-block;
      // width: 300px;
      margin-right: 1vw;
      margin-top: 10px;
      .selectTitle {
        // color: #333;
      }
      /deep/ .ant-select-selection{
        width: 165px;
      }
      /deep/ .ant-select-selection--multiple {
        width: 420px;
      }
    }
  }
  .searchVisible {
    height: 0px;
    overflow: hidden;
  }
}
.drawTabel {
  /deep/ .ant-table-scroll{
    min-height: calc(100vh - 440px);
  }
}
</style>